const router = require('koa-router')()
const Sequelize = require('sequelize')
const Op = Sequelize.Op
const jwt = require('jsonwebtoken')
const axios = require('axios')

const { Register } = require('../model/index')
const {sendCode,yancode} = require('../oss')

router.post('/login', async (ctx, next) => {
    let { email, password } = ctx.request.body
    let res = await Register.findOne({
        where: {
            email: email
        }
    })
    if (res) {
        let result = await Register.findOne({
            where: {
                email: email,
                password: password
            }
        })
        if (result) {
            // jwt.sign中
            // 第一个参数为token的值
            // 第二个参数为密钥
            // 第三个参数为token的过期时间
            const token = jwt.sign(
                {
                    email,
                    password
                },
                'test and verify',
                {
                    expiresIn: 3600 * 24 * 7
                }
            )
            // 写入cookie
            ctx.cookies.set('loginToken', token, {
                httpOnly: false
            })
            ctx.body = {
                code: 200,
                message: '登录成功',
                token,
                result
            }
        } else {
            ctx.body = {
                code: 400,
                message: '密码错误'
            }
        }

    } else {
        ctx.body = {
            code: 404,
            message: '用户不存在'
        }
    }

})

router.post('/register', async (ctx, next) => {
    let res = await Register.create({ ...ctx.request.body })
    ctx.body = {
        code: 200,
        message: '注册成功',
        res
    }
})

router.get('/sendmes', async (ctx, next) => {
    console.log("12233")
    const { phoneNum } = ctx.request.query
    console.log(phoneNum)
    const res = await sendCode(phoneNum)
    console.log(yancode,"333")
    ctx.body = {
        code:200,
        message:'短信发送成功',
        res,
        yancode
    }
})
module.exports = router